import axios from 'axios';
import Cookies from 'js-cookie';
import { Message } from 'element-ui';
// import { MessageBox, Message } from 'element-ui';
// import store from '@/store';
import { getToken } from '@/utils/auth';

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});
let lock = true;
// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers['X-Token'] = getToken();
    // }
    config.headers.Authorization = `Bearer${getToken()}`;
    // config.headers.Authorization = 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6eyJtb2JpbGUiOiIxODg4ODg4ODg4NSIsIm5hbWUiOiJhZG1pbiIsInVpZCI6IjkiLCJkaXN0cmljdENvZGUiOiI1MzAwMDAiLCJhdXRob3JpdGllcyI6W3siYXV0aG9yaXR5IjoiVVNFUiJ9LHsiYXV0aG9yaXR5IjoiQURNSU4ifSx7ImF1dGhvcml0eSI6IlNVUEVSX0FETUlOIn1dLCJ1c2VybmFtZSI6ImFkbWluIn0sImF1ZCI6WyJzZXJ2ZXIiLCJidXNpbmVzcyIsImFjaGlldmVtZW50IiwiYXBwcm92YWwiLCJjb2xsZWN0aW9uIiwidG9vbCIsImxhcmdlX3NjcmVlbiIsInN5c3RlbSIsImZpbGUiLCJjb21tb24iLCJnaXNfaW50cmFuZXQiLCJjb21wbGV0ZV9pbnRyYW5ldCIsInN5c3RlbV9pbnRyYW5ldCIsInNlYXJjaF9pbnRyYW5ldCIsImNvbXBsZXRlIiwiZGIiXSwidXNlcl9uYW1lIjoiYWRtaW4iLCJzY29wZSI6WyJhbGwiXSwiZXhwIjoxNjc5NjY5NTM2LCJhdXRob3JpdGllcyI6WyJVU0VSIiwiU1VQRVJfQURNSU4iLCJBRE1JTiJdLCJqdGkiOiIyNjhkZjFlMy1jMTc3LTQ4MTgtYjk1YS0zZGUzOTE5N2RkM2MiLCJjbGllbnRfaWQiOiJpbnRyYW5ldC1wYyJ9.gRtc9p9TtKmreV0O9EQBs9B1bC6HoGq_aqXmkTHS53mWWdt5QY17CrWOz1oOlvQAYoEzVgWugII0YLUQ8eZd1yIgerTKhU-bBLhehdbK9y0tvF_fN1hT3h-4QGOiiLsh6fVlJk0jwEdPk0qJ0V95oAL_NH_jnMCjYBn2X6TE5ZAhRkgkXQUY0Dh7QNzXoNOFrMvlpEbMAmeyi8drxkXNDJW2WGiAWRvZKupsM8NyGX97RfCarS60pC67uZ29XNhYqjgjEh_1_PSn4RuG7QbLx5WVVoTecvAPquv3G8yPzqfV4Y9c2yQZYvuKqK8YJXvbaKPUwkw2O3Rz-Y9gGEggSA';

    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  },
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;

    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000,
    //   });

    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm(
    //       'You have been logged out, you can cancel to stay on this page, or log in again',
    //       'Confirm logout',
    //       {
    //         confirmButtonText: 'Re-Login',
    //         cancelButtonText: 'Cancel',
    //         type: 'warning',
    //       },
    //     ).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         window.location.reload();
    //       });
    //     });
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'));
    // }
    return res;
  },
  (error) => {
    const { response } = error;
    if (response) {
      if (+response.status === 401) {
        Message.error('身份过期请重新登录');
        if (lock) {
          lock = false;
          setTimeout(() => {
            lock = true;
            Cookies.remove('token');
            // eslint-disable-next-line
            location.replace('/manager/login');
          }, 1000);
        }
      } else {
        Message.error(response.data.message);
      }
      // 提示错误信息并返回信息
      return response.data;
    }
    if (!window.navigator.onLine) {
      // 客户端断网
      Message.error('请检查网络');
    }
    return response;
  },
);

export default service;
